<?php
class TW_Router {

    public static function run(TW_Request $request) {

        $controller = $request->getController();
        $method = $request->getMethod();
        $args = $request->getArgs();

        $file = CONTROLLER_PATH . '/' . $controller . '.php';

        // Does the controller exist?
        if(file_exists($file)) {

            require_once($file);

            if(class_exists($controller)) {
                $controller = new $controller();
            } 
            else {
                self::error("Class '" . $controller . "' could not be found :(");
            }

            if(!is_callable(array($controller, $method))) {
                self::error("Method '" . $method . "' could not be found");
            }

            if(!empty($args)) {
                call_user_func_array(array($controller, $method), $args);
            }
            else {
                call_user_func(array($controller, $method));
            }

        }
        else {
            self::error("404 - Page '" . $request->getController() . "' could not be found");
        }

    }

    protected static function error($msg) {
        throw new Exception($msg);
    }

}